package com.luisliuyi.demo.optimize.network;

import android.text.TextUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

public class HttpCodec {
    static final String SPACE = " ";//一个空格
    static final String HTTP_VERSION = "HTTP/1.1";//http的版本信息
    static final String COLON = ":";//冒号
    static final String CRLF = "\r\n";
    //http响应中 13 http结束
    static final int CR = 13;
    static final int LF = 10;//换行的ASCII码
    private ByteBuffer byteBuffer;
    public HttpCodec(){
        byteBuffer = ByteBuffer.allocate(10 * 1024);
    }

    public void writeRequest(OutputStream os, Request request) {
        StringBuffer sb = new StringBuffer();
        sb.append(request.getMethod());
        sb.append(SPACE);
        sb.append(request.getHttpUrl().file);
        sb.append(SPACE);//一个空格
        sb.append(HTTP_VERSION);// HTTP/1.1
        sb.append("\r\n");//一个回车换行
        Map<String, String> headers = request.getHeaders();
        for(Map.Entry<String, String> entry : headers.entrySet()){
            sb.append(entry.getKey());
            sb.append(COLON);//一个冒号
            sb.append(SPACE);//一个空格
            sb.append(entry.getValue());
            sb.append(CRLF);//最后面跟一个回车和换行
        }
        sb.append(CRLF);//最后面跟一个回车和换行
        try {
            os.write(sb.toString().getBytes());
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean isEmptyLine(String line){
        return TextUtils.equals(line,CRLF);
    }

    public byte[] readBytes(InputStream is, int length) throws IOException {
        byte[] bytes = new byte[length];
        int readNum = 0;
        while(true){
            readNum = is.read(bytes,readNum,length - readNum);
            if(readNum == length){
                return bytes;
            }
        }
    }
    public Map<String, String> readHeaders(InputStream is) throws IOException {
        HashMap<String, String> headers = new HashMap<>();
        while(true) {
            String line = null;
            try {
                line = readLine(is);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (isEmptyLine(line)) {
                //如果读到空行 \r\n 响应头读完了
                break;
            }
            int index = line.indexOf(":");//因为服务器返回的响应头中的格式也是key: value的格式
            if (index > 0) {
                String key = line.substring(0, index);
                //这里加2 是因为，value前面还有冒号和空格，所以，value的第一个位置，需要往后移

                //减2是因为line后面有/r/n两个字节
                String value = line.substring(index + 2, line.length() - 2);
                headers.put(key, value);
            }
        }
        return headers;
    }

    public String readLine(InputStream is) throws Exception {
        byteBuffer.clear();
        byteBuffer.mark();
        byte b;
        boolean isMaybeEofLine = false;
        while((b = (byte)is.read()) != -1){
            byteBuffer.put(b);
            if(b == CR) {//如果读到一个 /r
                isMaybeEofLine = true;

            }
            if (isMaybeEofLine) {
                if(b == LF) {//如果读到一个 /n了，意味着，行结束了
                    byte[] lineBytes = new byte[byteBuffer.position()];//new一个一行数据大小的字节数据
                    byteBuffer.reset();
                    byteBuffer.get(lineBytes);
                    byteBuffer.clear();//清空
                    byteBuffer.mark();
                    return new String(lineBytes, "UTF-8");
                }
            }
        }
        return "";
    }

}
